package com.itbour.web.action.tg;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.util.StringUtils;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.tg.TypeInfoDto;
import com.itbour.dto.tg.OutlineInfoDto;
import com.itbour.service.tg.OutlineService;
import com.opensymphony.xwork2.ActionContext;
import com.qiniu.util.HttpRequest;
/**
 * copyright Itbour team 2016
 * 
 * @author xc
 */

public class GetOutlineWebAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private OutlineService outlineService;

	private String tgId;// 提纲id
	private String ids;// 删除/更新用id
	private String order;// 显示顺序

	private String typeIds;// 模版类型id
	private String userId;

	private List<TypeInfoDto> typeComboList;
	private OutlineInfoDto outlineInfo;

	private List<OutlineInfoDto> outlineInfoList = new ArrayList<OutlineInfoDto>();

	private String findPubFlg;// 检索条件
	private String findTmplName;// 检索条件
	private String findTmplType;// 检索条件
	private String findMstFlg;// 检索母版
	HashMap<String, Object> mapResult = new HashMap<String, Object>();// 检索结果

	/**
	 * 导出提纲信息
	 * @throws Exception
	 */
	public void downDocStats() throws Exception {
		String API_SVR = "https://api.itbour.com";
		//String API_SVR = "http://120.27.141.121:3000";
		//API_SVR = "http://192.168.31.252:3000";// for Debug
		
		HttpServletRequest request = ServletActionContext.getRequest();
		Integer tgId = Integer.parseInt(request.getParameter("tg_id"));
		StringBuilder sb = new StringBuilder();
		String SEP = ",";
		Date date = new Date();
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sim2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String date1 = sim.format(date);
		String date2 = sim2.format(date);
		String getPageInfo = HttpRequest.sendGet(API_SVR+"/v5/api4back/getTgUserDocCnt",
				"pageSize=20&tgId="+tgId);
	   JSONObject jsonPage = JSONObject.fromObject(getPageInfo);
	   String msg=jsonPage.get("msg").toString();
	   if("成功".equals(msg)){
		    JSONObject jsonData=(JSONObject) jsonPage.get("data");
		    Integer pageCount = (Integer) jsonData.get("pageCount");
		    String tJson=HttpRequest.sendGet(API_SVR+"/v5/api4back/getTgUserDocText",
					"pageNum=0&pageSize=1&tgId=" + tgId);
		    JSONObject tFJson=JSONObject.fromObject(tJson);
		    JSONObject tData=(JSONObject) tFJson.get("data");
			sb.append("提纲ID:").append(SEP).append(tgId).append("\n");
			sb.append("用户文档信息:").append(SEP).append(date1).append("\n");
			@SuppressWarnings("unchecked")
			List<String> list = (List<String>) tData.get("titles");
			int listSize=list.size();
			sb=sb.append("UserDocID:");
			for (int i = 0; i < listSize; i++) {
				sb=sb.append(SEP).append(list.get(i));
			}
			sb.append("\n");
			for (int j = 0; j < pageCount; j++) {
				String s = HttpRequest.sendGet(API_SVR+"/v5/api4back/getTgUserDocText",
						"pageNum="+j+"&pageSize=20&tgId=" + tgId);
				JSONObject json = JSONObject.fromObject(s);
				Object obj=json.get("data");
				if(obj!=null){
					JSONObject data = (JSONObject)obj;
					JSONArray jsonArray = JSONArray.fromObject(data.get("list"));
					for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject listData = (JSONObject) jsonArray.get(i);
					@SuppressWarnings("unchecked")
					List<String> textList = (List<String>) listData.get("texts");
					int textSize=textList.size();
						sb=sb.append("\""+listData.get("id")+"\"");
						for (int k = 0; k < textSize; k++) {
							sb=sb.append(SEP).append("\"" + Null2Str(textList.get(k)) + "\"");
						}
						sb.append("\n");
					}
				 }
			}
			String fileName = "TG_"+tgId+"_UserDocInfo_" + date2 + ".csv";
	        String output = sb.toString();
	        HttpServletResponse response = ServletActionContext.getResponse();
	        response.addHeader("Content-Disposition", "attachment; filename="+fileName); 
	        response.setContentType("application/octet-stream"); 
	        response.setCharacterEncoding("UTF8"); 
	        response.getWriter().write(output); 
	        response.flushBuffer();
	   }
	}

	private String Null2Str(Object in) {
		return (in == null) ? "" : String.valueOf(in);
	}

	// 获取提纲分类
	public String getTypeForCombo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String parent = request.getParameter("parent");
		String flg = request.getParameter("blkFlg");
		String topIds = request.getParameter("topIds");// 逗号连接顶级分类
		Map<String, Object> param = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(parent)) {
			param.put("parent", parent);
		}
		if (StringUtils.isNotBlank(topIds)) {
			param.put("topIds", topIds);
		}
		typeComboList = outlineService.getTypeForCombo(param);
		if (typeComboList != null && typeComboList.size() > 0) {
			// 添加空白项目
			if ("1".equals(flg)) {
				TypeInfoDto blankItem = new TypeInfoDto();
				blankItem.setType_id(0L);
				blankItem.setType_name("[不限]");
				typeComboList.add(0, blankItem);
			}

			// 默认选中第一个
			typeComboList.get(0).setSelected(true);
		}
		return SUCCESS;
	}

	// 修改提纲显示顺序
	public void updOutlineOrder() throws Exception {
		if (StringUtils.isNotBlank(tgId)) {
			Map<String, Object> session = ActionContext.getContext().getSession();
			UserInfoDto user = (UserInfoDto) session.get("user");
			// update
			if (user != null && user.getUser_id() != null) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("order", order);
				param.put("tg_id", tgId);
				param.put("update_by", user.getUser_id() + user.getUser_name());
				outlineService.updateOutlineById(param);
			}
		}
		this.writeJSON("ok");
	}

	// 取消发布
	public void cancelPublish() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			Map<String, Object> session = ActionContext.getContext().getSession();
			UserInfoDto user = (UserInfoDto) session.get("user");
			if (user != null && user.getUser_id() != null) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("publish", 0);
				param.put("ids", StringUtils.listToString2(StringUtils
						.stringToList2(ids)));
				param.put("update_by", user.getUser_id() + user.getUser_name());
				outlineService.updateOutlineById(param);
			}
		}
		this.writeJSON("ok");
	}

	// 发布提纲
	public void doPublish() throws Exception {
		// ids: ","连接
		if (StringUtils.isNotBlank(ids)) {
			Map<String, Object> session = ActionContext.getContext().getSession();
			UserInfoDto user = (UserInfoDto) session.get("user");
			if (user != null && user.getUser_id() != null) {

				List<Long> listId = StringUtils.stringToList2(ids);
				// TODO check

				// update
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("publish", 1);
				param.put("ids", StringUtils.listToString2(listId));
				param.put("update_by", user.getUser_id() + user.getUser_name());
				outlineService.updateOutlineById(param);
			}
		}
		this.writeJSON("ok");
	}

	// 获取提纲模版
	public String getOutlineTmpl() throws Exception {

		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> param = new HashMap<String, Object>();
		String id = request.getParameter("tgId");
		if (StringUtils.isNotEmpty(id)) {
			param.put("tg_id", id);
		}
		param.put("del_flg", 0);

		outlineInfoList = outlineService.selectOutlineInfo(param);
		return SUCCESS;
	}

	// 获取提纲模版列表
	public String getOutlineTmplList() throws Exception {
		// 用户信息
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user = (UserInfoDto) session.get("user");
		if (user != null && user.getUser_id() != null) {
			HttpServletRequest request = ServletActionContext.getRequest();
			String pageNumber = request.getParameter("page");
			String pageSize = request.getParameter("rows");
			Map<String, Object> param = new HashMap<String, Object>();
			if (StringUtils.isNotBlank(findTmplType)
					&& Long.valueOf(findTmplType) > 0L) {
				param.put("type_id", findTmplType);
			}
			if (StringUtils.isNotBlank(findPubFlg)) {
				param.put("publish", findPubFlg);
			}
			if (StringUtils.isNotEmpty(findTmplName)) {
				param.put("tg_name", "%" + findTmplName + "%");
			}

			if (!user.isSuperUser()) {
				param.put("user_id", user.getUser_id());// 默认只检索自己的文档
			}

			if (StringUtils.isEqual(findMstFlg, "1")) {
				param.put("master", "1");// 检索提纲模版
			} else {
				param.put("master", "0");// 检索普通提纲
			}
			Page page = outlineService.pageQuery(param,
					Integer.parseInt(pageNumber), Integer.parseInt(pageSize));
			HashMap<String, Object> resMap = new HashMap<String, Object>();
			resMap.put("total", page.getTotalCount());
			resMap.put("rows", page.getResult());
			// writeJSON(resMap);
			mapResult = resMap;
		} else {
			mapResult.clear();
		}

		return SUCCESS;
	}

	// 删除提纲
	public void deleteOutline() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user = (UserInfoDto) session.get("user");
		if (user != null && user.getUser_id() != null) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("ids",
					StringUtils.listToString2(StringUtils.stringToList2(ids)));
			param.put("update_by", user.getUser_id() + user.getUser_name());
			outlineService.deleteOutlineInfo(param);
			this.writeJSON("ok");
		} else {
			this.writeJSON("ng");
		}
	}

	// 新规提纲
	public void addOutline() throws Exception {
		if (outlineInfo != null) {
			Map<String, Object> session = ActionContext.getContext().getSession();
			UserInfoDto user = (UserInfoDto) session.get("user");
			if (user != null) {
				outlineInfo.setUpdate_by(user.getUser_name());
				outlineInfo.setUser_id(user.getUser_id());
				// outlineInfo.setUser_type(user.getUser_type());
			}

			outlineService.addOutlineInfo(outlineInfo);
		}
		this.writeJSON("ok");
	}

	// 更新提纲信息(编辑器用)
	public void updOutline() throws Exception {
		HashMap<String, Object> resMap = new HashMap<String, Object>();

		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user = (UserInfoDto) session.get("user");
		if (user != null) {

			HttpServletRequest request = ServletActionContext.getRequest();
			String paramId = request.getParameter("id");
			String paramMstId = request.getParameter("mstId");// 提纲模版id
			String paramName = request.getParameter("name");
			String paramData = request.getParameter("data");
			String ver = request.getParameter("ver");// 版本号，201610281602

			// id不为空:更新
			if (StringUtils.isNotBlank(paramId)) {

				// 非超级用户需要check
				if (!user.isSuperUser()) {
					// user_id, tg_id关联check
					Map<String, Object> chkParam = new HashMap<String, Object>();
					chkParam.put("tg_id", Long.valueOf(paramId.trim()));
					chkParam.put("user_id", user.getUser_id());
					chkParam.put("del_flg", 0);
					List<OutlineInfoDto> chkList = outlineService
							.selectOutlineInfo(chkParam);
					if (chkList == null || chkList.size() == 0) {
						resMap.put("status", "ng");
						resMap.put("msg", "本文档禁止修改！");
						this.writeJSON(resMap);
						return;
					}
				}

				// 更新提纲数据
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("tg_id", Long.valueOf(paramId.trim()));
				param.put("tg_name", paramName);
				param.put("ver", Integer.valueOf(ver));// 版本号，201610281602
				param.put("data", paramData);
				param.put("update_by", user.getUser_id().toString());
				outlineService.updateOutlineById(param);

				// 返回值
				resMap.put("tgId", paramId);

				// id为空:新规
			} else {
				// 新规提纲数据
				OutlineInfoDto info = new OutlineInfoDto();
				info.setData(paramData);
				info.setTg_name(paramName);
				info.setVer(Integer.valueOf(ver));// 版本号，201610281602
				info.setType_id(0L);// 默认未分类
				if (StringUtils.isNotBlank(paramMstId)&& Long.valueOf(paramMstId) > 0L) {
					info.setMaster(0);// 普通提纲
					info.setBase_tg_id(Long.valueOf(paramMstId));// 提纲模版id

					Map<String, Object> param = new HashMap<String, Object>();
					param.put("tg_id", Long.valueOf(paramMstId));
					param.put("master", 1);
					List<OutlineInfoDto> retTgMst = outlineService
							.selectOutlineInfo(param);
					if (retTgMst != null && retTgMst.size() > 0) {
						info.setType_id(retTgMst.get(0).getType_id());// 设置分类
					}

				} else {
					info.setMaster(1);// 提纲模版
					info.setBase_tg_id(null);
				}
				info.setPublish(0);// 默认制作中
				info.setUser_id(user.getUser_id());
				info.setUpdate_by(user.getUser_id().toString());
				Long newId = outlineService.addOutlineInfo(info);

				// 返回值
				resMap.put("tgId", newId);
			}

			resMap.put("status", "ok");
			this.writeJSON(resMap);
			return;
		}

		resMap.put("status", "ng");
		this.writeJSON(resMap);
	}

	// 更新提纲分类
	public void updOutlineType() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user = (UserInfoDto) session.get("user");
		if (user != null) {
			HttpServletRequest request = ServletActionContext.getRequest();
			String paramTgId = request.getParameter("tgId");
			String paramTypeId = request.getParameter("typeId");

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tg_id", Long.valueOf(paramTgId.trim()));
			param.put("type_id", Long.valueOf(paramTypeId.trim()));
			param.put("update_by", user.getUser_id().toString());
			outlineService.updateOutlineById(param);
			this.writeJSON("ok");

		} else {
			this.writeJSON("ng");
		}
	}

	// 设置fast
	public void setOutlineFast() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user = (UserInfoDto) session.get("user");
		if (user != null) {
			HttpServletRequest request = ServletActionContext.getRequest();
			String paramTgId = request.getParameter("tgId");
			String paramTypeId = request.getParameter("typeId");

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tg_id", Long.valueOf(paramTgId.trim()));
			param.put("type_id", Long.valueOf(paramTypeId.trim()));
			param.put("update_by", user.getUser_id().toString());
			// 检查是否可设fast属性
			int cnt = outlineService.chkOutlineFast(param);
			if (cnt > 0) {
				// 取消旧fast提纲
				outlineService.deleteOutlineFastByType(param);

				// 设置新fast提纲
				param.remove("type_id");
				param.put("fast", 1);
				outlineService.updateOutlineById(param);

				this.writeJSON("ok");
				return;
			}
		}

		this.writeJSON("ng");
	}

	public OutlineService getOutlineService() {
		return outlineService;
	}

	public void setOutlineService(OutlineService outlineService) {
		this.outlineService = outlineService;
	}

	public List<OutlineInfoDto> getOutlineInfoList() {
		return outlineInfoList;
	}

	public void setOutlineInfoList(List<OutlineInfoDto> outlineInfoList) {
		this.outlineInfoList = outlineInfoList;
	}

	public List<TypeInfoDto> getTypeComboList() {
		return typeComboList;
	}

	public void setTypeComboList(List<TypeInfoDto> typeComboList) {
		this.typeComboList = typeComboList;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getFindTmplType() {
		return findTmplType;
	}

	public void setFindTmplType(String findTmplType) {
		this.findTmplType = findTmplType;
	}

	public String getFindPubFlg() {
		return findPubFlg;
	}

	public void setFindPubFlg(String findPubFlg) {
		this.findPubFlg = findPubFlg;
	}

	public String getFindTmplName() {
		return findTmplName;
	}

	public void setFindTmplName(String findTmplName) {
		this.findTmplName = findTmplName;
	}

	public String getFindMstFlg() {
		return findMstFlg;
	}

	public void setFindMstFlg(String findMstFlg) {
		this.findMstFlg = findMstFlg;
	}

	public HashMap<String, Object> getMapResult() {
		return mapResult;
	}

	public void setMapResult(HashMap<String, Object> mapResult) {
		this.mapResult = mapResult;
	}

	public String getTgId() {
		return tgId;
	}

	public void setTgId(String tgId) {
		this.tgId = tgId;
	}

	public OutlineInfoDto getOutlineInfo() {
		return outlineInfo;
	}

	public void setOutlineInfo(OutlineInfoDto outlineInfo) {
		this.outlineInfo = outlineInfo;
	}

	public String getTypeIds() {
		return typeIds;
	}

	public void setTypeIds(String typeIds) {
		this.typeIds = typeIds;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

}
